package blue.mqtt4j.internal.client.impl;

import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttPublishVariableHeader;
import io.netty.handler.codec.mqtt.MqttQoS;

/**
 * @author Jin Zheng
 * @since 1.0 2020-10-22
 */
public class PublishMessage
{
	private int messageId = -1;
	private MqttQoS qos;
	private MqttMessageType type;
	private MqttMessage message;
	private int delay;
	private long sendTime;

	public PublishMessage(MqttMessage message, int delay)
	{
		Object header = message.variableHeader();
		if (header != null)
		{
			if (header instanceof MqttPublishVariableHeader)
			{
				this.messageId = ((MqttPublishVariableHeader) header).messageId();
			}
			else if (header instanceof MqttMessageIdVariableHeader)
			{
				this.messageId = ((MqttMessageIdVariableHeader) header).messageId();
			}
		}
		this.qos = message.fixedHeader().qosLevel();
		this.type = message.fixedHeader().messageType();
		this.message = message;
		this.delay = delay;
		this.sendTime = System.currentTimeMillis() + delay;
	}

	public PublishMessage buildNew()
	{
		return new PublishMessage(message, delay);
	}

	public int messageId()
	{
		return messageId;
	}

	public MqttQoS qos()
	{
		return qos;
	}

	public MqttMessageType type()
	{
		return type;
	}

	public MqttMessage message()
	{
		return message;
	}

	public int delay()
	{
		return delay;
	}

	public long sendTime()
	{
		return sendTime;
	}
}
